package org.setamv.springcloud.hystrix.comprehesive;

import org.setamv.springcloud.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Configuration
@RestController
@RequestMapping("/greetings")
public class GreetingsController {

    @Autowired
    private GreetingsService greetingsService;

    @RequestMapping(value = "/from/{yourName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String greetings(@PathVariable String yourName) {
        String greetings = greetingsService.greetings(yourName);
        return greetings;
    }

    /**
     * 使用Hystrix的缓存。注意，要使用Hystrix缓存，必须初始化HystrixRequestContext，该对象是在ServletFilter {@link HystrixContextInitFilter}中初始化的
     * @param yourName
     * @return
     */
    @RequestMapping(value = "/from/{yourName}/cached", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String greetingsFromCache(@PathVariable String yourName) {
        // 这里调用3次，看看是否会有2次是从缓存取的。如果下面重复调用3次，只打印了1次日志，说明有2次根本没有执行方法
        String greetings = "";
        for (int i = 0; i < 3; i++) {
            greetings = greetingsService.greetings(yourName);
        }
        // 删除缓存
        greetingsService.removeCache(yourName);
        // 再次访问，因为前面已经删除缓存，这里会再次实现非缓存的访问
        greetingsService.greetings(yourName);
        return greetings;
    }
}
